import { Vector3 } from './Vector3'

export const CalculateCenter = {
    lonLatCenterPoint (position: Array<Vector3>): Vector3 {
        let total: number = position.length;
        if (total === 0) {
            return new Vector3(0, 0, 0)
        }
        let X: number = 0;
        let Y: number = 0;
        let Z: number = 0;
        let totalHeight: number = 0;
        position.forEach((coordinate: Vector3) => {
            let lat: number = coordinate.y * Math.PI / 180;
            let lon: number = coordinate.x * Math.PI / 180;
            let height: number = coordinate.z; 
            totalHeight += height;
            X += Math.cos(lat) * Math.cos(lon);
            Y += Math.cos(lat) * Math.sin(lon);
            Z += Math.sin(lat);
        });
    
        X = X / total;
        Y = Y / total;
        Z = Z / total;
        let lon2: number = Math.atan2(Y, X);
        let hyp: number = Math.sqrt(X * X + Y * Y);
        let lat2: number = Math.atan2(Z, hyp);
        let avgHeight: number = totalHeight / total;
        const coordinatect= new Vector3(lon2 * 180 / Math.PI,lat2 * 180 / Math.PI,avgHeight)
        return coordinatect;
    },
    mathCenterPoint(pointList: Array<Vector3>): Vector3 {
        let centerPoint: Vector3 = new Vector3();
        let totalHeight: number = 0;
        let maxX = Number.MIN_SAFE_INTEGER;
        let minX = Number.MAX_SAFE_INTEGER;
        let maxY = Number.MIN_SAFE_INTEGER;
        let minY = Number.MAX_SAFE_INTEGER;
    
        for (let i = 0; i < pointList.length; i++) {
            totalHeight += pointList[i].z;
    
            maxX = Math.max(maxX, pointList[i].x);
            minX = Math.min(minX, pointList[i].x);
            maxY = Math.max(maxY, pointList[i].y);
            minY = Math.min(minY, pointList[i].y);
        }
    
        centerPoint.x = (maxX + minX) / 2;
        centerPoint.y = (maxY + minY) / 2;
        centerPoint.z = totalHeight / pointList.length;
    
        return centerPoint;
    }
    
}